<template>
    <div class="dhzn_goods">    
        <!-- 子路由的导航头 -->
        <div v-if="this.$route.matched.length === 2" class="dhzn-gson bcwh br5">
            <div class="dhzn_gs-title bcwh">
                <!-- <span><i class="el-icon-arrow-left f24 b00a"></i></span> -->
                <span>商品详情</span>
                <router-link to="/goods" class="br5 bc4a f14 wh pt5 pb5 pl5 pr5">返回</router-link>
            </div>
            <div class="dhzn_gs-content bcwh">
                <el-menu :default-active="activeSon" router class="dhzn_gscn-menu mb10" mode="horizontal" @select="handleSelect">
                    <el-menu-item :index="'/goods/gdactivity/'+this.$route.params.aid">商品活动</el-menu-item>
                    <el-menu-item :index="'/goods/gdcoupon/'+id">商品优惠券</el-menu-item>
                    <el-menu-item :index="'/goods/gddetails/'+id">商品详情</el-menu-item>
                    <el-menu-item :index="'/goods/gdsize/'+id">商品规格</el-menu-item>
                    <el-menu-item :index="'/goods/gdsevalu/'+id">商品评价</el-menu-item>
                    <el-menu-item :index="'/goods/gdsevimg/'+id">评价图片</el-menu-item>
                    <el-menu-item :index="'/goods/gdsmaterial/'+id">商品轮播图</el-menu-item>
                    <el-menu-item :index="'/goods/gdserve/'+id">商品服务</el-menu-item>
                </el-menu>
                <!-- <span>{{activeSon}}</span> -->
                <router-view></router-view>
            </div>
        </div>
        <!-- 主路由的商品列表 -->
        <div v-else>
            <div class="d_g-list p10" v-if="paging <= 2">
                <div>
                    <!-- 查询，目前只支持名字，种类，价格以及商家四项 -->
                    <div class="d_g-l-query">

                        <el-form :inline="true" :model="form" class="demo-form-inline">
                            <el-form-item label="查询名称">
                                <el-input v-model="form.name" placeholder="请输入产品名称" clearable></el-input>
                            </el-form-item>
                            <el-form-item label="查询分类">
                                <el-select v-model="form.kindid" placeholder="选择查询的产品分类" clearable>
                                    <el-option v-for="(item,key) in options" :key="key" :label="item.grade>1 ? '|----|'+item.label : item.label" :value="item.value" />
                                </el-select>
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" @click="onSubmit">查询</el-button>
                            </el-form-item>
                        </el-form>

                    </div>

                    <div class='d_g-l-title mb10 mt10'>
                        <button type="button" class="bc4a wh pt5 pb5 br5" @click="augment">添加商品+</button>
                    </div>

                    <div class="d_g-l-data">

                        <table class="d_gld-table tc">

                            <thead>
                                <tr>
                                    <th>商品编号</th>
                                    <th>商品名称</th>
                                    <th>单品销量</th>
                                    <th>商品图片<br/><span class="n f12 ff53">(*点击查看大图)</span></th>
                                    <th>生产农户</th>
                                    <th>销售商家</th>
                                    <th>产品分类</th>
                                    <th>产品状态</th>
                                    <th>操作</th>
                                </tr>
                            </thead>

                            <tbody>
                                <tr v-for="(item,key) in goodsdata" :key="key">
                                    <td>{{item.id}}</td>
                                    <td class="tl d_gldt-name">
                                        <h1 class="f16">{{item.name}}</h1>
                                        <p>价格:<span class="red">{{item.price}}</span></p>
                                        <router-link :to="'/goods/gdactivity/'+ item.id">查看详情</router-link>
                                        <!-- <router-link to="/goodsdetails">查看详情</router-link> -->
                                    </td>
                                    <td>{{item.salesVolume}}</td>
                                    <td class="">
                                        <el-popover placement="top" popper-class="d_gld-t-popover" trigger="click" v-model="item.visible">
                                            <img :src="item.level===1 ? 'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=37453093,1676265439&fm=26&gp=0.jpg' : item.imageurl">
                                            <img slot="reference" :src="item.level===1 ? 'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=37453093,1676265439&fm=26&gp=0.jpg' : item.imageurl">
                                        </el-popover>
                                        <!-- <img :src="item.imageurl" alt=""> -->
                                    </td>
                                    <td>{{item.farmerid}}</td>
                                    <td>{{item.businessid}}</td>
                                    <td>{{item.kindid}}</td>
                                    <td>
                                        <el-switch
                                            class="switch"
                                            @change="shelfswitch(item)"
                                            v-model="item.shelf"
                                            :active-value="1"
                                            :inactive-value="0"
                                            active-text="上架"
                                            inactive-text="下架">
                                        </el-switch>
                                        <div class="d_gldt-activea">
                                            <el-select size="mini" v-model="item.active" @change="activeadd(item.id,item.active,key)" placeholder="选择参加活动">
                                                <el-option v-for="(items,keys) in goodsactive" :key="keys" :label="items.name" :value="items.id"></el-option>
                                            </el-select>
                                        </div>
                                    </td>
                                    <td>
                                        <button type="button" class="dh_glpt-t-btn bc4a wh pt5 pr10 pb5 pl10 br5 f16" @click="updatagoods(item,key)"><i title="修改" class="f16 iconfont icon-xiugai"></i>编辑</button>
                                        <button type="button"  class="dh_glpt-t-btn bcfd wh pt5 pr10 pb5 pl10 br5 f16" @click="detgoods(item.id,key)"><i title="删除" class="f16 iconfont icon-shanchu"></i>删除</button>
                                    </td>
                                </tr>
                            </tbody>

                        </table>
                    </div>
                </div>

                <div class="d_g-lblock mt20">
                    <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="currentPage"
                        :page-size="pagesize"
                        layout="total, prev, pager, next, jumper"
                        :total="total">
                    </el-pagination>
                </div>

            </div>

            <div class="d_g-add" v-else>

                <div class="d_g-a-title">
                    <span v-if="paging === 3">添加商品</span><span v-else-if="paging === 4">修改商品</span><button @click="paging = 1" type="button" class="bor1 br5 f12 bcwh ml10">返回列表</button>
                </div>

                <div class="d_g-a-details mt60">
                    <el-form label-width="120px">
                        <el-form-item label="上级分类">
                            <el-select v-model="form.kindid" placeholder="请选择添加分类的上级分类">
                                <!-- <el-option label="顶级" :value="0"></el-option> -->
                                <el-option v-for="(item,key) in options" :key="key" :label="item.level>1 ? '|----|'+item.name : item.name" :value="item.id"></el-option>
                            </el-select>
                            
                        </el-form-item>

                        <!-- 多选的下拉选框效果 -->
                        <!-- <div class="block">
                            <span class="demonstration">默认显示所有Tag</span>
                            <el-cascader
                                :options="options"
                                :props="props"
                                clearable></el-cascader>
                        </div> -->

                        <el-form-item v-for="(item,key) in addgoods" :key="key" :label="item.name">
                            <el-input v-model="item.value" :disabled="paging == 4 ? item.state : false" :placeholder="'请输入需要创建的'+item.name"></el-input>
                        </el-form-item>

                        <el-form-item label="商品状态">
                            <el-radio v-model="form.shelf" label="1">上架</el-radio>
                            <el-radio v-model="form.shelf" label="0">下架</el-radio>
                        </el-form-item>

                        <el-form-item><el-button type="primary" @click="goodsadd">提交</el-button></el-form-item>
                    </el-form>
                </div>

            </div>
        </div>
         
    </div>
</template>

<script>
const axios = require('axios')
let that
export default {
    components: {},
    data() {
        return {
            token: '',
            id: '',
            paging: 1,                           //同一页面内显示不同的多个页面的内容
            goodsname: [],
            goodsimag: [],
            // 产品数据
            goodsdata: [],
            // 添加新产品的数组
            addgoods: [
                {name:'商品名称',value:''},
                {name:'商品价格',value:''},
                {name:'佣金返现',value:''},
                {name:'商品对应的农户',value:'',state: true},
                {name:'商品对应的商家',value:'',state: true},
            ],
            options: [],                      //选框下拉数组
            props: { multiple: true },
            form:{
                kindid:'',
                shelf: '',
                name: ''
            },
            pageingstate: 0,
            currentPage: 1,						//分页的默认页数
            pagesize: 10,                       //单页条数
            total: 0,						   //总条数
            activeone: '',
            activeSon: '',
        };
    },
    computed: {},
    watch: {
        // 监听路由变化
        $route(to,from){
            // console.log(to.path,from);
        },
        // 监听路由传值变化
        $route: {
            handler() {
                if(this.$route.params.aid !== ''){
                    this.id = this.$route.params.aid;
                    //   this.getDetail();
                    // console.log(this.id)
                }

                if(this.$route.matched.length === 2){
                    // that.$route.matched(路由路径，包括子级路由都有，返回数组)
                    let navrouter = this.$route.matched[1].path || '/';
                    // 路由拼接，拿到的传参路由是键名定义的，转成键值（上面接收的方法）
                    this.activeSon = navrouter.substr(0,navrouter.length-4)+this.id;
                    // console.log(this.activeSon)
                }else{return}
              
                //   console.log(this.$route.params.aid)
                //深度监听，同时也可监听到param参数变化
            },
            deep: true,
        }
        // console.log(that.$route.params.aid)
    },
    methods: {
        // 请求图片
        async requestimage(){
            let that = this;
            let total = 10;
            let data = {current:1,size:100000000};
            let updata = JSON.stringify(data);
            axios({
                method: 'post',
                url: '/api/goodsBanner/list',
                headers: {
                    'Content-type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            }).then(resp=>{
                console.log(resp)
                let obj = {};
                that.goodsimage = resp.data.data.reduce((item,next) => {
                    obj[next.goodsid] ? '' : obj[next.goodsid] = true && item.push(next)
                    return item
                },[])
                that.goodslist()
                // console.log(that.goodsimage)
            }).catch(err=>{console.log(err)})


        },

        // 单页条数
        handleSizeChange(val) {
            // console.log(`每页: ${val}条数据`);
            this.pagesize = val;
            this.goodslist()
        },

        //分页的跳页函数
        handleCurrentChange(val) {
            // console.log(`当前页: ${val}`);
            const that = this;
            that.currentPage = val;
            that.goodslist()
        },

        // 顶部导航
        handleSelect(key, keyPath) {
            // console.log(key, keyPath);
        },

        // 商品请求
        goodslist(){
            const that = this;
            let data = {current:that.currentPage,size:that.pagesize};
            let updata = JSON.stringify(data)
            // console.log(that.goodsimage)
            axios({
                method: 'post',
                url: '/api/goods/list',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`,
                },
                data: updata
            })
            .then( resp=> {
                console.log(resp)
                resp.data.data.forEach((item)=>{
                    item.active = '';
                })
                that.goodsdata = resp.data.data;
                // 把商品的id和商品名拿出来搞成数组，用于显示id对应的商品
                that.goodsname = resp.data.data.map((item) => {
                    return{
                        id: item['id'],
                        name: item['name']
                    }
                })
                sessionStorage.setItem("goodsdata",JSON.stringify(that.goodsname))
                // console.log(data)

                if(that.goodsdata === undefined){
                    sessionStorage.removeItem("token")
                    location.reload()
                }else{
                    // console.log('报错点',resp.data.data)
                    that.total = resp.data.code;
                    resp.data.data.forEach(item=>{
                        that.goodsimage.forEach(itemson=>{
                            if(item.id === itemson.goodsid){ 
                                item.imageurl = itemson.imageurl
                            }
                        })
                    })
                }    
                // console.log(that.selectdata)            
            })
            .catch( err=> {console.log(err)})
        },
        
        //添加修改产品时有个原数据，需要进入前清空一下，修改会有个赋值，问题补打，添加没有
        augment(){
            let that = this;
            that.paging = 3
            for(var o in that.form)
            that.form[o] = '';
            for(var r=0;r<that.addgoods.length;r++){
                that.addgoods[r].value = '';
            }
        },

        // 增加商品
        goodsadd(){
            let that = this;
            let data = {},api;
            if(that.paging === 3){
                api = '/api/goods/add'
            }else if(that.paging === 4){
                api = '/api/goods/update'
                data.id = that.form.id
            }
            data.name = that.addgoods[0].value;
            data.price = that.addgoods[1].value;
            data.commission = that.addgoods[2].value;
            data.farmerid = that.addgoods[3].value;
            data.businessid = that.addgoods[4].value;
            data.kindid = that.form.kindid;
            data.shelf = Number(that.form.shelf);
            for(var i in data)
            if(data[i] === ''){
                delete data[i]
            }
            let updata = JSON.stringify(data)
            console.log(updata,data)
            axios({
                method: 'post',
                url: api,
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`,
                },
                data: updata
            })
            .then( resp=> {
                // console.log(resp.data.data)
                if(that.paging === 3){
                    that.goodsdata.push(data)
                }else if(that.paging === 4){
                    that.goodsdata.splice(that.form.key,1,data)
                }
                that.paging = 1;
            })
            .catch( err=> {console.log(err)})
        },

        //添加活动
        activeadd(id,active,key){
            let that = this;
            let data = {goodsid:id,indexActivityid:active};
            let updata = JSON.stringify(data)
            axios({
                method: 'post',
                url: '/api/indexGoods/add',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`    
                },
                data: updata
            }).then(resp=>{
                console.log(resp)
                if(resp.data.message === '请求成功'){
                    this.$message({
                        message: "成功参加活动",
                        type: 'success'
                    })
                }else{return}
            }).catch(err=>{console.log(err)})
        },

        // 删除
        detgoods(upid,key){
            let that = this;
            let data = {id: upid}
            let updata = JSON.stringify(data)
            axios({
                method: 'post',
                url: "/api/goods/delete",
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`,
                },
                data: updata
            })
            .then( resp=> {
                //console.log(resp.data.data)
                that.goodsdata.splice(key,1)
            })
            .catch( err=> {console.log(err)})
        },

        // 修改（所有关于产品的信息）
        updatagoods(item,key){
            let that = this;
            that.paging = 4;
            // console.log(item,key,typeof(item.shelf))
            that.form.kindid = item.kindid;
            that.form.shelf = String(item.shelf);
            that.addgoods[0].value = item.name;
            that.addgoods[1].value = item.price;
            that.addgoods[2].value = item.commission;
            that.addgoods[3].value = item.farmerid;
            that.addgoods[4].value = item.businessid;
            that.form.id = item.id;
            that.form.key = key
        },

        // 修改产品状态（上下架）
        shelfswitch(item){
            let that = this;
            let data = {
                id: item.id,
                name: item.name,
                price: item.price,
                businessid: item.businessid,
                shelf: item.shelf
            };
            let updata = JSON.stringify(data)
            axios({
                method: 'post',
                url: "/api/goods/update",
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`,
                },
                data: updata
            })
            .then( resp=> {
                //console.log(resp.data.data)
            })
            .catch( err=> {console.log(err)})
        },

        // 获取全部分类，剔除分类等级大于2级的，用于选框的分类等级
        dump(){
            const that = this;
            let data = {current:that.currentPage,size:that.pagesize};
            let updata = JSON.stringify(data)
            // console.log(that.goodsimage)
            axios({
                method: 'post',
                url: '/api/kind/list',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`,
                },
                data: updata
            })
            .then( resp=> {
                // console.log(resp.data.data)
                // 对象重命名
                that.options = resp.data.data.map((item)=>{
                    return {
                        value: item['id'],
                        label: item['name'],
                        grade: item['level']
                    }
                });
                if(that.goodsdata === undefined){
                    sessionStorage.removeItem("token")
                    location.reload()
                }else{return}               
            })
            .catch( err=> {console.log(err)})
        },

        // 查询搜索
        onSubmit(){
            let that = this;
            that.paging = 2;
            let data = {
                current:that.currentPage,
                size:that.pagesize,
                name: that.form.name,
                kindid: that.form.kindid
            };
            for(var u in data)
            if(data[u] === ''){
                delete data[u]
            }
            let updata = JSON.stringify(data)
            axios({
                method: 'post',
                url: '/api/goods/list',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`,
                },
                data: updata
            })
            .then( resp=> {
                // console.log(resp.data.data)
                that.goodsdata = resp.data.data;
                that.total = resp.data.code;
            })
            .catch( err=> {console.log(err)})
        },

        // 查看商品详情(轮播图、活动、优惠券)
        goodsdetails(id){
            let that = this;
        },

        //拿全部的活动
        requestactive(){
            let that = this;
            let data = {current:1,size:1000000000};
            let updata = JSON.stringify(data);
            axios({
                method: 'post',
                url: '/api/indexActivity/list',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            }).then(resp=>{
                //console.log("活动",resp)
                that.goodsactive = resp.data.data.map((item)=>{
                    return{
                        id: item['id'],
                        name:item['name']
                    }
                })
                // console.log(that.goodsactive)
            }).catch(err=>{console.log(err)})
        },
        
        //拿token
        newtoken(){
            let that = this;
            let axios = require('axios')
			let loguser = JSON.parse(sessionStorage.getItem('updata'))
			let data = {username:loguser.username, password:loguser.password};
			let updata = JSON.stringify(data);
			console.log(updata)
			axios({
				method: 'post',
				url: '/api/getAuthority/manager',
				headers: { 'Content-Type': 'application/json' },
				data: updata
			})
			.then( resp=> {
                that.token = resp.data.data;
				sessionStorage.setItem("token", JSON.stringify(resp.data.data))        
                that.requestimage()
                that.dump()
                that.requestactive()
			}).catch( err=> {})
        }
    },
    created() {
        let that = this;
        // console.log(this.$route.matched)
        if(that.$route.params.aid !== 0){
            that.id = that.$route.params.aid;
        }
        // 刷新保持导航路由不变
        if(that.$route.matched.length === 2){
            // that.$route.matched(路由路径，包括子级路由都有，返回数组)
            let navrouter = that.$route.matched[1].path || '/';
            // 路由拼接，拿到的传参路由是键名定义的，转成键值（上面接收的方法）
            that.activeSon = navrouter.substr(0,navrouter.length-4)+that.id;
            // console.log(that.activeSon)
        }else{return}
        
        // this.activeSon = this.$route.matched[1].name
        // console.log(this.$route.params.aid)
    },
    mounted() {
        let that = this;
        if(that.$route.params.aid !== 0){
            that.id = that.$route.params.aid;
        }
        // 刷新保持导航路由不变
        if(that.$route.matched.length === 2){
            // that.$route.matched(路由路径，包括子级路由都有，返回数组)
            let navrouter = that.$route.matched[1].path || '/';
            // 路由拼接，拿到的传参路由是键名定义的，转成键值（上面接收的方法）
            that.activeSon = navrouter.substr(0,navrouter.length-4)+that.id;
            // console.log(that.activeSon)
        }
        that.newtoken()
        
    },

    beforeCreate() {},
    beforeMount() {},
    beforeUpdate() {},
    updated() {},
    beforeDestroy() {},
    destroyed() {},
    activated() {},
    filters: {
        goodsarrfilter(kindid){
            console.log(this.goodsname)
            this.goodsname.filter((item) =>{ 
                if(item.id === kindid){
                    kind =  item.name
                }
            })
            return goodsid
        },        
    },
}
</script>
<style>
    .dhzn_goods{
        height: calc(100% - 56px);
        box-sizing: border-box;
    }

    /* 列表 */
    .d_g-list{
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        width: 100%;
        height: 100%;
        background-color: #ffffff;
    }

    /* 搜索 */
    .d_g-l-query{
        border-bottom: 1px solid #f3f3f3;
    }
    .d_g-l-query .el-form-item{
        margin: 10px 0;
    }

    /* 数据列表 */
    .d_gld-table{
        width: 100%;
        color: #666666;
        border-bottom: 1px solid #e0e0e0;
        border-left: 1px solid  #e0e0e0;
        border-collapse: collapse;
    }
    .d_gld-table thead tr{
        background-color: #F2F2F2;
    }
    .d_gld-table tbody tr:hover{
        background-color: #F2F2F2;
    }
    .d_gld-table th, .d_gld-table td{
        min-height: 50px;
        padding: 10px;
        border-top: 1px solid #e0e0e0;
        border-right: 1px solid #e0e0e0;
    }
    /* 图片大小的 */
    .d_gld-table tr td img{
        max-width: 120px;
        max-height: 80px;
    }
    /* 左边的图片预览效果 */
    .d_gld-t-popover img{
        max-width: 500px;
        max-height: 500px;
    }
    /* 写在产品名称中的查看按钮 */
    .d_gldt-n-check{
        font-size: 14px;
        color: #409EFF;
        cursor: pointer;
    }

    .demo-form-inline .el-select{
        width: 100%;
    }
    /* 开关样式修改 */
    .el-switch__label {
        position: absolute;
        display: none;
        font-size: 11px !important;
        color: #fff!important;
    }
    .el-switch__label *{
        font-size: 11px !important;
    }
    /*打开时文字位置设置*/
    /* switch按钮样式 */
    .switch .el-switch__label {
        position: absolute;
        display: none;
        color: #fff !important;
    }
    /*打开时文字位置设置*/
    .switch .el-switch__label--right {
        z-index: 1;
    }
    /* 调整打开时文字的显示位子 */
    .switch .el-switch__label--right span{
        margin-right: 13px;
    }
    /*关闭时文字位置设置*/
    .switch .el-switch__label--left {
        z-index: 1;
    }
    /* 调整关闭时文字的显示位子 */
    .switch .el-switch__label--left span{
        margin-left: 13px;
    }
    /*显示文字*/
    .switch .el-switch__label.is-active {
        display: block;
    }
    /* 调整按钮的宽度 */
    .switch.el-switch .el-switch__core,
    .el-switch .el-switch__label {
        width: 50px !important;
        margin: 0;
    }

/* 子级页面导航 */
.dhzn-gson{
    height: 100%;
    padding: 10px;
    box-sizing: border-box;
}
.dhzn_gs-title{
    /* display: flex;
    align-items: center;
    justify-content: space-between; */
    height: 50px;
    line-height: 50px;
    font-size: 17px;
    /* border-bottom: 1px solid #bbbbbb; */
}

/* 导航栏跟数据列表 */
.dhzn_gs-content{
    height: calc(100% - 50px);
}
.dhzn_gscn-menu .el-menu-item{
    font-size: 15px;
    height: 40px;
    line-height: 40px;
    padding: 0;
}
.el-menu--horizontal>.el-menu-item.is-active{
    border-bottom: 4px solid #409EFF
}
.dhzn_gscn-menu>.el-menu-item+.el-menu-item{
    margin-left: 20px;
}

/* 添加活动 */
.d_gldt-activea{
    width: 120px;
    margin: 0 auto;
    margin-top: 10px;
}
</style>